using System;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using E4RPDevExpress;
using ZecaFil.DataSet;

namespace ZecaFil.Controls
{
    public partial class ServiceDesignationXtraUserControl : XtraUserControl, IGridView
    {
        private Controller _controller;

        #region Properties

        public Controller Controller
        {
            set
            {
                _controller = value;
                _controller.ServiceDesignationSaved += delegate { SetGridDataSource(); };
                SetGridDataSource();
            }
        }

        #endregion

        public ServiceDesignationXtraUserControl()
        {
            InitializeComponent();
            gridView.DoubleClick += GridViewDoubleClick;
        }
        
        #region Private Methods

        private void SetGridDataSource()
        {
            DesignacaoServicoDataSet dataSet = _controller.GetServiceDesignations();
            gridControl.DataSource = null;
            gridControl.DataSource = dataSet;
            gridControl.DataMember = dataSet.DesignacaoServico.TableName;
        }

        private void ShowDocument(string documentId)
        {
            var window = new ServiceDesignationXtraForm() { DocumentId = documentId, Controller = _controller };
            window.ShowDialog();           
        }

        #endregion

        public void AddDocument()
        {
            ShowDocument("");
        }

        public GridView GridView()
        {
            return gridView;
        }

        public string ListName
        {
            get { return "ServiceDesignationXtraUserControl"; }
        }
        
        void GridViewDoubleClick(object sender, EventArgs e)
        {
            var document = (DesignacaoServicoDataSet.DesignacaoServicoRow)gridView.GetDataRow(gridView.FocusedRowHandle);
            if (document == null)
                return;
            ShowDocument(document.Codigo);
        }
    }
}
